import { addRole, updateRole } from '@/services/system/SystemController';
import {
  ModalForm,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { message } from 'antd';

export interface RoleType {
  id: number;
  name: string;
  key: string;
  description: string;
  data_scope: number;
  status: boolean;
}

const RoleForm: React.FC<{
  data: RoleType | null | 0;
  onClose: () => void;
  onFinish: () => void;
}> = ({ data, onClose, onFinish }) => {
  let is_new = data !== null && data === 0;
  let id = data !== null && data !== 0 ? data.id : 0;
  const { loading, run: postResource } = useRequest((data) => { return is_new ? addRole(data) : updateRole(id, data) }, {
    manual: true,
    throwOnError: true,
    onSuccess() { message.success('操作成功'); onFinish(); }
  })
  return (
    <ModalForm<RoleType>
      title={is_new ? '新增' : '编辑'}
      open={data !== null}
      width={450}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: onClose,
      }}
      layout="horizontal"
      submitTimeout={2000}
      loading={loading}
      onFinish={postResource}
    >
      <div className='py-2'></div>
      <ProFormText
        name="name"
        label="角色名称"
        placeholder="请输入角色名称"
        initialValue={(data !== 0 && data?.name) || ''}
        rules={[{ required: true, message: '请输入至少三个字符！', min: 3 }]}
      />
      <ProFormText
        name="key"
        label="权限字符"
        placeholder="请输入权限字符"
        initialValue={(data !== 0 && data?.key) || ''}
        rules={[{ required: true, message: '请输入至少三个字符！', min: 3 }]}
      />

      <ProFormSelect
        name="data_scope"
        label="数据权限"
        initialValue={data !== 0 && data?.data_scope}
        required
        options={[{ value: 1, label: "所有数据权限" }, { value: 3, label: "本部门及以下数据权限" }, { value: 4, label: "本部门数据权限" }, { value: 5, label: "仅本人数据权限" }]}
      />
      <ProFormSwitch
        name="status"
        label="状态"
        required
        initialValue={is_new ? true : data !== 0 && data?.status}
      />
      <ProFormTextArea
        name="description"
        label="角色描述"
        placeholder="请输入角色描述"
        initialValue={(data !== 0 && data?.description) || ''}
      />
    </ModalForm>
  );
};

export default RoleForm;
